package com.lagou.java;

import java.util.Random;

public class ServerInfo implements Comparable<ServerInfo>{
    // 超时时间
    public static int TIME_OUT = 5000;

    // 服务端 ip
    private String host;

    // 服务端 端口
    private Integer port;

    private Integer expiredTime;

    @Override
    public int hashCode() {
        return (host + port).hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if(obj == null || !(obj instanceof ServerInfo) ) return false;
        ServerInfo info = (ServerInfo)obj;
        if (info.getHost().equals(host) && info.getPort().intValue() == port.intValue()) {
            System.out.println("info.getHost().equals(host)" + info.getHost().equals(host));
            System.out.println("info.getPort() == port" + (info.getPort() == port));
            return true;
        }
        return false;
    }

    // 获取服务端地址
    public String getAddress() {
        return this.host.trim() + ":" + this.port;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public Integer getExpiredTime() {
        return expiredTime;
    }

    public void setExpiredTime(Integer expiredTime) {
        this.expiredTime = expiredTime;
    }

    @Override
    public String toString() {
        return "ServerInfo{" +
                "host='" + host + '\'' +
                ", port=" + port +
                ", expiredTime=" + expiredTime +
                '}';
    }


    /**
     * hash set 返回值时， 不能为 0, 否则当用到 SortedSet 子类时， 新值将无法插入
     * @param o
     * @return
     */
    @Override
    public int compareTo(ServerInfo o) {
        boolean oOK = !(o == null || o.getExpiredTime() ==  null || o.getExpiredTime() + TIME_OUT < System.currentTimeMillis());
        boolean thisOk = !(this.expiredTime == null || this.getExpiredTime() + TIME_OUT < System.currentTimeMillis());

        if (!oOK && !thisOk) return getRandom();
        if(oOK && !thisOk) return -1;
        if(thisOk && !oOK) return 1;
        return this.getExpiredTime() - o.getExpiredTime() > 0 ? 1 : -1;
//        return 1;
    }

    private int getRandom () {
        return new Random().nextInt(10) % 2 == 0 ? 1 : -1;
    }

}
